package com.study.controller;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder.In;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.study.model.mdao.DeportFormMapper;
import com.study.model.pojo.Depotgoodsshelf;
import com.study.model.pojo.Good;
import com.study.model.pojo.Inst;
import com.study.model.pojo.Payplan;
import com.study.model.pojo.Scheduleform;
import com.study.model.pojo.Supplier;
import com.study.model.vo.CartBox;
import com.study.model.vo.CartBoxpur;
import com.study.services.DeportService;
import com.study.services.DepotgoodsshelfService;
import com.study.services.DictionaryService;
import com.study.services.GoodsService;
import com.study.services.InstService;
import com.study.services.PayPlanService;
import com.study.services.PayRecordService;
import com.study.services.PurchaseService;
import com.study.services.ScheduleFormService;
import com.study.services.SupplierManService;
import com.study.services.SupplierService;
import com.study.util.MaxId;
import com.study.util.NumberForm;

@Controller
public class ScheduleFormController {
	@Autowired
	ScheduleFormService service;
	@Autowired
	DictionaryService dis;
	@Autowired
	SupplierService sup;
	@Autowired
	SupplierManService sm;
	@Autowired
	DepotgoodsshelfService ds;
	@Autowired
	GoodsService goodsService;
	@Autowired
	PurchaseService ps;
	@Autowired
	PayPlanService pService;
	@Autowired
	PayRecordService prs;
	@Autowired
	DeportService dservice;
	@Autowired
	DeportService deportService;
	@Autowired
	DeportFormMapper deportFormMapper;
	
	/**
	 * 查询所有采购单
	 * @return
	 */
	@GetMapping("/purchaseList")
	@ResponseBody
	public ModelAndView purchase() {
		ModelAndView mv = new ModelAndView("/goods/purchaselist");
		return mv;
	}
	
	/**
	 * 条件查询
	 * @return
	 */
	@PostMapping("/purchaseList")
	@ResponseBody
	public String selectByPage(HttpSession session) {
		Integer userid = (Integer) session.getAttribute("useid");
		List<JSONObject> list = service.selectBySel(1, 10, "", "","",userid);
		PageInfo<JSONObject> pager = new PageInfo<JSONObject>(list);
        String json = JSONObject.toJSONString(pager);
		System.out.println(json);
		return json;
	}
	
	/**
	 * 带条件查询
	 * @return
	 */
	@PostMapping("/purlist")
	@ResponseBody
	public String getForm3(String supname,String theme,
			String selects,
			int currentPage,
			int pagesize,
			HttpSession session,HttpServletRequest request) {
		System.out.println(selects+"===="+supname+"======"+theme);
		Integer userid = (Integer) session.getAttribute("useid");
		List<JSONObject> list = service.selectBySel(currentPage, pagesize, supname.trim(),theme.trim(), selects.trim(),userid);
		PageInfo<JSONObject> pager = new PageInfo<JSONObject>(list);
		String json = JSONObject.toJSONString(pager);
		return json;
	}
	
	
	
	/**
	 * 跳转添加采购单
	 * @return
	 */
	@RequestMapping("/purchaseAdd")
	public ModelAndView purchaseAdd() {
		ModelAndView mv = new ModelAndView("/goods/purchaseForm");
		//查询所有仓库
		List<JSONObject> sto = ds.selectAll();
		//可关联的订单
		List<JSONObject> order = service.queryLinkOrder();
		System.out.println("可关联订单："+order);
		//查询所有供应商
		mv.addObject("sps", sup.findAll(null));
		//axios查询供应商下的联系人
		mv.addObject("order", order);
		mv.addObject("sto", sto);
		return mv;
	}
	
	@PostMapping("/querySupman")
	@ResponseBody
	public JSONObject selectByName(HttpServletRequest request) {
		String supno = request.getParameter("id");
		System.out.println("供应商id是:"+supno);
		List<JSONObject> list = sm.selectBySupno(Integer.parseInt(supno));
		System.out.println("联系人："+list);
		JSONObject jso = new JSONObject();
		jso.put("supman", list);// 放入联系人
		return jso;
	}
	
	/**
	 * 跳转采购单详情
	 * @return
	 */
	@RequestMapping("/purchasedesc")
	public ModelAndView purchasedetail(HttpSession session,HttpServletRequest request) {
		String schno = request.getParameter("id");
		if (schno==null) {
			schno = (String) session.getAttribute("sch");
		}
		System.out.println("进来没有"+schno);
		session.setAttribute("schid", schno);
		
		JSONObject list = service.findById(schno);
		Object json = JSON.toJSON(list);
		// 获取中文金额
		StringBuffer test = NumberForm.test(((JSONObject) json).getInteger("schsum"));
		//付款计划的显示
		JSONObject record = pService.selectplan(Integer.parseInt(schno));
		//付款记录
		Payplan plan = record.toJavaObject(record, Payplan.class);
		ModelAndView mv = new ModelAndView("/goods/purchasedesc");
		if (plan!=null) {
			JSONObject note = prs.queryId(plan.getPayid());
			mv.addObject("note", note);//付款记录
		}
		List<JSONObject> li = ps.query(Integer.parseInt(schno));
		((JSONObject) json).put("big", test);
		mv.addObject("list",list);
		mv.addObject("li", li);
		mv.addObject("record", record);//付款计划
		session.removeAttribute("schno");
		return mv;
	}
	
	
	
	
	/**
	 * 跳转到采购明细界面
	 * 
	 * @param oid
	 * @param session
	 * @return
	 */
	@RequestMapping("/purchasedetail")
	public ModelAndView goodsMx(HttpSession session,HttpServletRequest request) {
		String schno = request.getParameter("schno");
		System.out.println("采购单号为======："+schno);
		ModelAndView mv = new ModelAndView("/goods/purchasedetail");
		//===========================================
		CartBoxpur cart = (CartBoxpur) session.getAttribute("pur");
		if (cart == null) {
			cart = new CartBoxpur();
		}
		//ps.findDetail(Integer.parseInt(schno), cart);
		System.out.println("刚开始的购物车：" + cart);
		session.setAttribute("schid", schno);
		JSONObject jsonObj = (JSONObject) JSON.toJSON(cart);
		System.out.println("bean2Json()方法：jsonObj==" + jsonObj);
		session.setAttribute("pur", cart);
		session.setAttribute("purlist", jsonObj);
		mv.addObject("schno", schno);
		return mv;
		//===========================================
	}

	/**
	 * 添加一个商品到订单明细中
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping("/addpurchasedetail")
	@ResponseBody
	public CartBoxpur addGoods(int ids, HttpSession session) {
		System.out.println("添加一条商品数据获得的id是什么呢？？？" + ids);
		CartBoxpur cart = (CartBoxpur) session.getAttribute("pur");
		if (cart == null) {
			cart = new CartBoxpur();
		}
		cart.addProduct(goodsService.findByGoodsIdByVo(ids));
		System.out.println("当前购物车...：" + cart.getMap());

		JSONObject jsonObj = (JSONObject) JSON.toJSON(cart);
		session.setAttribute("pur", cart);
		//session.setAttribute("purlist", jsonObj);
		return cart;
	}

	/**
	 * 修改商品数量
	 * 
	 * @param ids
	 * @param quatitys
	 * @param session
	 * @return
	 */
	@PostMapping("/updatepurchaseToCart")
	@ResponseBody
	public CartBoxpur updateGoodsQuatitys(int ids, int quatitys, HttpSession session) {

		System.out.println("修改商品数量处的id是什么？？？：" + ids + " quatitys：" + quatitys);
		CartBoxpur cart = (CartBoxpur) session.getAttribute("pur");
		cart.modifyproductQuatity(ids, quatitys, cart);

		System.out.println("修改后当前购物车：" + cart.getMap());
		session.setAttribute("pur", cart);
		return cart;
	}

	/**
	 * 删除商品信息
	 * 
	 * @param ids
	 * @param session
	 * @return
	 */
	@PostMapping("/deletepurchaseToCart")
	@ResponseBody
	public CartBoxpur deleteGoods(int ids, HttpSession session) {
		System.out.println("商品编号为：" + ids);
		CartBoxpur cart = (CartBoxpur) session.getAttribute("pur");
		System.out.println(cart.getMap());
		cart.deleteProduct(ids, cart);
		System.out.println("当前购物车：" + cart.getMap());
		session.setAttribute("pur", cart);
		return cart;
	}
	
	/**
	 * 提交订单明细 并跳转回订单详情页面
	 * 
	 * @param ids
	 * @param quatitys
	 * @param session
	 * @return
	 * @return
	 */
	@PostMapping("/submitpurchaseDetails")
	@ResponseBody
	public JSONObject submitGoods(HttpSession session,HttpServletRequest request) {
		CartBoxpur cart = (CartBoxpur) session.getAttribute("pur");
		//Integer schno = (Integer) session.getAttribute("schid");
		String para = request.getParameter("id");
		Integer schno = Integer.parseInt(para);
		System.out.println("提交采购单明细成功了吗？？？采购单号是多少？"+schno);
		System.out.println("当前购物车有：" + cart);
		System.out.println("当前采购单id是:" + schno);
		ps.delete(schno);// 删除对应采购单id的采购详情
		ps.addDetail(schno, cart);// 添加对应采购单id的采购详情
		JSONObject object = new JSONObject();
		object.put("schno", schno);
		//session.removeAttribute("pur");
		return object;
	}
	
	/**
	 * 新建采购单
	 * @param theme
	 * @param supno
	 * @param linId
	 * @param userid
	 * @param date1
	 * @param stock
	 * @param date2
	 * @param type
	 * @param money
	 * @param linkorder
	 * @param remark
	 * @return 
	 */
	@PostMapping("/addpurchase")
	@ResponseBody
	public void add(String theme,Integer supno,Integer linId,Integer userid,
					Date date1,Integer stock,Date date2,Integer type,
					Integer orderid,String remark,HttpSession session) {
		System.out.println("供应商id：--"+supno+"====\n经手人："+userid+"==分类："+type+"/n==供应商联系人id："+linId);
		
		Supplier s = sup.queryByid(supno);
		Depotgoodsshelf dt = ds.selectById(stock);
		Scheduleform sf = new Scheduleform();
		sf.setTheme(theme);
		sf.setUserid(userid);
		sf.setSupplier(s);
		sf.setSchsum(new BigDecimal(0));
		sf.setSchtime(date1);
		sf.setSchpretime(date2);
		sf.setSctype(type);
		if (orderid!=null) {
			sf.setOid(orderid);
		}
		sf.setPtype(0);
		sf.setSchstates(3185);
		sf.setDepotgoodsshelf(dt);
		sf.setRemark(remark);
		sf.setSdel(1);
		sf.setPayed(new BigDecimal(0));
		service.insert(sf);
	}
	
	/**
	 * 生成入库单
	 * @param request
	 */
	@PostMapping("/updateform")
	@ResponseBody
	public void updatestates(Integer id,HttpSession session) {
		Integer userid = (Integer) session.getAttribute("useid");
		CartBoxpur cart = (CartBoxpur) session.getAttribute("pur");
		System.out.println("这个是空的？？"+cart);
		Inst inst = new Inst();
		//获得数据库id最大值存为
		Integer fll = null;
		Integer findMaxId = deportFormMapper.findMaxId();
		System.out.println(findMaxId);
		if (findMaxId != null && findMaxId != 0) {
			fll = findMaxId;
		}
		String innum = MaxId.generateNewOrderID2(fll);
		//根据id查询入库单
		//Scheduleform plan = service.sele(id);
		JSONObject plan = service.sele(id);
		System.out.println("仓库是多少？？"+plan.getString("dgsnum"));
		//新增一条入库单
		inst.setInnum(Integer.parseInt(innum));
		inst.setTheme(plan.getString("theme"));//获得主题
		
		Depotgoodsshelf dp=new Depotgoodsshelf();
		dp.setDgsnum(Integer.parseInt(plan.getString("dgsnum")));//获得仓库对象
		inst.setDepotgoodsshelf(dp);
		
		inst.setTdate(new Date());
		
		Scheduleform sf=new Scheduleform();
		sf.setSchno(id);
		inst.setScheduleform(sf);
		
		inst.setCwnum(userid);
		inst.setIntype(3022);
		inst.setInshow(1);
		dservice.insert(inst);
		//修改采购单状态
		service.selectById(id);
		//添加入库明细
		deportService.addinsDetail(inst.getInnum(), cart);
		session.removeAttribute("pur");
	}
	
	/**
	 * 删除采购单
	 * @param goo_id
	 * @return
	 */
	@PostMapping("/delpurchase")
	@ResponseBody
	public String delete(Integer schno) {
		System.out.println(schno);
		service.delete(schno);
		return "/purcahseList";
	}
	
}
